package cc.rboot.trigger.aspect;

import cc.rboot.trigger.configuration.RBootEventTriggerConfiguration;
import cc.rboot.trigger.core.IEventTrigger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Aspect
@Component
public class EventTriggerAspect {

    @Resource
    RBootEventTriggerConfiguration reactiveRegistry;

    @Pointcut("execution(public * *.onReactor(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if (joinPoint.getTarget() instanceof IEventTrigger) {
            Object result = joinPoint.proceed();

            List<IEventTrigger> reactiveEventList = reactiveRegistry.getEventReactorList(joinPoint.getTarget().getClass());
            for (IEventTrigger event : reactiveEventList) {
                event.onTrigger(joinPoint.getArgs()[0]);
            }
            return result;
        }
        return joinPoint.proceed();
    }
}
